<?php
namespace app\api\controller;

use think\Controller;
use app\common\lib\exception\ApiException;
use app\common\lib\Aes;
use app\common\lib\IAuth;
use app\common\lib\Time;
use think\Cache;
/**
 * API模块 公共的控制器
 */
class Common extends Controller
{
    /**
     * [$headers header头信息]
     * @var string
     */
    public $headers = "";


    /**
     * [$page 第几页]
     * @var string
     */
    public $page = '';


    /**
     * [$size 每页多少条]
     * @var string
     */
    public $size = '';


    /**
     * [$from 查寻条件的起始值]
     * @var integer
     */
    public $from = 0;



    /**
     * [_initialize 初始化的方法]
     * @return [type] [description]
     */
    public function _initialize(){
        $this->checkRequestAuth();
        // $this->testAes();
    }

    /**
     * [checkRequestAuth 检查每次app请求的数据是否合法]
     * @return [type] [description]
     */
    public function checkRequestAuth(){
        // 首先获取headers
        $headers = request()->header();
        //todo
        //sign 加密需要  客户端工程师,   解密:服务端工程师
        // 1 headers body 仿照sign 做参数加解密
        // 2
        //

        //基础参数校验
        if (empty($headers['sign'])) {
            throw new ApiException('sign不存在',400);
        }

        if (!in_array($headers['app-types'],config('app.apptypes'))) {
            throw new ApiException('apptypes类型不合法',400);
        }
        //需要sign
        if (!IAuth::checkSignPass($headers)) {
            throw new ApiException("授权sign失败", 401);
        }

        Cache::set($headers['sign'],1,config('app.app_sign_cache_time'));
        //sign的唯一性
        //1.文件 2.mysql 3.redis
        $this->headers = $headers;

    }


    public function testAes(){
        $data = [
            'did' => '12345dg',
            'version' => 1,
            'time' => Time::get13TimeStamp(),
        ];
        // halt($data);

        echo IAuth::setSign($data);exit;

    }



    protected function getDealNews($news){
        if (empty($news)) {
            return [];
        }

        $cats = config('cat.lists');
        foreach ($news as $key => $new) {
            $news[$key]['catname']=$cats[$new['catid']]?$cats[$new['catid']]:'-';
        }

        return $news;
    }

        /**
     * [getPageAndSize 获取分页page size值]
     * @return [type] [description]
     */
    public function getPageAndSize($data){
        $this->page = !empty($data['page'])?$data['page']:1;//当前页
        $this->size = !empty($data['size'])?$data['size']:config('paginate.list_rows');
        $this->form = ($this->page-1)*$this->size;
    }

}
